import React, { useEffect, useState } from 'react';
import { Space, Table, Tag } from 'antd';
import request from '../../api/request'
import { Button, message, Popconfirm } from 'antd';
import { UserOutlined ,ShoppingOutlined,DeleteOutlined,EditOutlined} from '@ant-design/icons';
import {  Checkbox, Form, Input } from 'antd';
import {  Modal } from 'antd';
import {  Drawer } from 'antd';
import { Pagination } from 'antd';
function Index() {
    const [data,setData]=useState([])
    const [keyword,setKeyword]=useState('')
    // 新增编辑标题
    const [title,setTitle]=useState('')
    const [addFrom]=Form.useForm()
    // 编辑
    const [edit,setEdit]=useState('')
    // 分页
    const [count,setCount]=useState(0)
    const [page,setPage]=useState(1)
    const [pageSize,setPageSize]=useState(10)
    const getData=()=>{
      request.get('/article/list',{
        params:{
            keyword,
            page,
            pageSize
        }
      }).then((res)=>{
         console.log(res)
         setData(res.data.rows)
      setCount(res.data.count)
      })
    }
    useEffect(()=>{
        getData()
    },[keyword,page,pageSize])
    // 分页
    const onChange = (page,pageSize) => {
        setPage(page)
        setPageSize(pageSize)
    getData()
    }
    // 二次删除
    const confirm = (id)=> {
   const arr=data.filter((item)=>item.id!==id)
   setData(arr)
   alert('删除陈工')
};
const cancel = e => {
  console.log(e);
  message.error('Click on No');
};
// 下架
const dell=(id)=>{
       const arr=data.filter((item)=>item.id!==id)
   setData(arr)
   alert('下架成功')
}
// 搜索
const onFinish = values => {
  console.log('Success:', values);
  setKeyword(values.keyword)
};
const onFinishFailed = errorInfo => {
  console.log('Failed:', errorInfo);
};
// 新增对话框
const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
//   新增按钮 
const add=()=>{
    setIsModalOpen(true)
    setTitle('新增')
    addFrom.resetFields('')
}
// 新增表单
const addonFinish = values => {
  console.log('Success:', values);
    if(title=='新增'){
         request.post('/article',
    {
title:values.title,//文章标题
content:values.content,//文章内容
tagList:["HTTP"],//标签  array[string]
categoryList:["HTTP"],//分类  array[string]
authorId:47529555//用户id 暂时写死47529555 登陆成功后返回的用户信息
    }
  ).then((res)=>{
    alert('新增成功')
    setIsModalOpen(false)
    getData()
  })
    }else{
        request.put(`/article/${edit}`,{
            title:values.title,//文章标题
content:values.content,//文章内容
tagList:["HTTP"],//标签  array[string]
categoryList:["HTTP"],//分类  array[string]

        }).then((res)=>{
      alert('编辑成功')
     setIsModalOpen(false)
       getData()
        })
    }
};
const addonFinishFailed = errorInfo => {
  console.log('Failed:', errorInfo);
};
// 编辑按钮
const bian=(record)=>{
    setIsModalOpen(true)
    setTitle('编辑')
    setEdit(record.id)
    addFrom.setFieldsValue({
        title:record.title,
        content:record.content
    })
}
// 详情抽屉
 const [open, setOpen] = useState(false);
const [qw,setQw]=useState('')
  const showDrawer = (id) => {
    setOpen(true);
    request.get(`/article/${id}`,{
        params:{
            id
        }
    }).then((res)=>{
setQw(res.data)
    })
  };

  const onClose = () => {
    setOpen(false);
  };
//   分页
    const columns = [
  {
    title: '序号',
    dataIndex: 'id',
    key: 'id',
    render: text => <a>{text}</a>,
  },
  {
    title: '博客标题',
    dataIndex: 'title',
    key: 'title',
  },
  {
    title: '作者',
    dataIndex: 'content',
    key: 'content',
  },
  {
    title: '标签',
    dataIndex: '',
    key: '',
    // 标签
      render: () => <Tag color="blue">标签</Tag>,
  },
  {
    title: '大图',
    dataIndex: '',
    key: '',
  },
    {
    title: '状态',
    dataIndex: '',
    key: '',
    // 标签已发布
    render: () => <Tag color="green">已发布</Tag>,
  },
     {
    title: '更新时间',
    dataIndex: 'updatedAt',
    key: 'updatedAt',
  },
     {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
  },
  {
    title: 'Action',
    key: 'action',
    render: (_, record) => (
      <Space size="middle">
          <Button icon={<EditOutlined />} onClick={()=>bian(record)}></Button>
       <Popconfirm
    title="Delete the task"
    description="Are you sure to delete this task?"
    onConfirm={()=>confirm(record.id)}
    onCancel={cancel}
    okText="删除"
    cancelText="取消"
  >
    <Button danger icon={<DeleteOutlined />}></Button>
  </Popconfirm>
    <Button type="primary" onClick={()=>dell(record.id)}>
       下架
      </Button>
    <Button type="primary" onClick={()=>showDrawer(record.id)}>
       详情
      </Button>
      </Space>
    ),
  },
];
  return (
    <div>
        {/* 详情 */}
       
      <Drawer
        title="详情"
        closable={{ 'aria-label': 'Close Button' }}
        onClose={onClose}
        open={open}
      >
        <p>{qw.title}</p>
        <p>{qw.content}</p>
      </Drawer>
        {/* 新增 */}
        <Button onClick={add}>新增博客</Button>
           <Modal
        title={title}
        closable={{ 'aria-label': 'Custom Close Button' }}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
       <Form
       form={addFrom}
    name="basic"
    labelCol={{ span: 8 }}
    wrapperCol={{ span: 16 }}
    style={{ maxWidth: 600 }}
    initialValues={{ remember: true }}
    onFinish={addonFinish}
    onFinishFailed={addonFinishFailed}
    autoComplete="off"
  >
    <Form.Item
      label="标题"
      name="title"
      rules={[{ required: true, message: 'Please input your username!' }]}
    >
      <Input />
    </Form.Item>
      <Form.Item
      label="作者"
      name="content"
      rules={[{ required: true, message: 'Please input your username!' }]}
    >
      <Input />
    </Form.Item>
   
    <Form.Item label={null}>
      <Button type="primary" htmlType="submit">
        Submit
      </Button>
    </Form.Item>
  </Form>
      </Modal>

        {/* 搜索 */}
         <Form
         layout='inline'
    name="basic"
    labelCol={{ span: 8 }}
    wrapperCol={{ span: 16 }}
    style={{ maxWidth: 600 }}
    initialValues={{ remember: true }}
    onFinish={onFinish}
    onFinishFailed={onFinishFailed}
    autoComplete="off"
  >
    <Form.Item
      label="博客标题"
      name="keyword"
      rules={[{ required: true, message: 'Please input your username!' }]}
    >
      <Input />
    </Form.Item>
    <Form.Item label={null}>
      <Button type="primary" htmlType="submit">
        Submit
      </Button>
    </Form.Item>
  </Form>
     <Table columns={columns} dataSource={data} 
     
     Pagination={{
   total:count,
    showSizeChanger:true,
    showQuickJumper:true,
    showTotal:(total) => `Total ${total} items`,
      onchange:onChange,
     }}
 
     />
    </div>
  )
}

export default Index
